
import sqlite3

class RecoDB():
    def __init__(self):
        #连接数据库，如果库不存在就创建，再连接
        self.conn = sqlite3.connect("./data/reco.db",check_same_thread=False)
        #创建表
        self.create_table()
    def create_table(self):
        #创建表(表不存在就创建)
        c = self.conn.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS tb_featrue
            (id INTEGER PRIMARY KEY AUTOINCREMENT,
            name           TEXT    NOT NULL,
            img_path       TEXT     NOT NULL,
            age             INT     default 0,
            feature        BLOB     NOT NULL);''')
        print ("数据表创建成功")
        self.conn.commit()

    def insert(self,name, img_path, feature ):
        """"存储数据
            feature : 传入是numpy
        """
        cmd = '''INSERT INTO tb_featrue (name, img_path, feature) VALUES (?, ?, ?);'''
        c = self.conn.cursor()
        feature = feature.tobytes()# 特征由numpy转二进制再存
        c.execute(cmd, (name, img_path, feature))
        self.conn.commit()

    def read_tb_featrue(self):
        cmd = '''SELECT name, img_path, feature FROM tb_featrue;'''
        c = self.conn.cursor()
        rows = c.execute(cmd)       
        return rows

